<?php

/**
 * This is the model class for table "schedule".
 *
 * The followings are the available columns in table 'schedule':
 * @property integer $idschedule
 * @property integer $iduser
 * @property integer $team_id
 * @property integer $idshift
 * @property integer $idqshift
 * @property integer $idweekday
 *
 * The followings are the available model relations:
 * @property Shift $idshift0
 * @property Weekday $idweekday0
 * @property User $iduser0
 * @property Qshift $idqshift0
 * @property Team $team
 */
class Schedule extends CActiveRecord
{

     private $_wasChanged = false;
     private $_changeId = null;
	 private $_isQshiftChange = false;

     public function getWasChanged(){
         return $this->_wasChanged;
     }

     public function setWasChanged($newValue){
         $this->_wasChanged = $newValue;
     }

     public function getChangeId(){
         return $this->_changeId;
     }

     public function setChangeId($id){
         $this->_changeId = $id;
     }
		 
     public function getIsQshiftChange(){
         return $this->_isQshiftChange;
     }

     public function setIsQshiftChange($newValue){
         $this->_isQshiftChange = $newValue;
     }
		 

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Schedule the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'schedule';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('iduser, team_id, idshift, idqshift, idweekday', 'required'),
			array('iduser, team_id, idshift, idqshift, idweekday', 'numerical', 'integerOnly'=>true),
			array('idqshift', 'checkShiftQshiftHours'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('idschedule, iduser, team_id, idshift, idqshift, idweekday', 'safe', 'on'=>'search'),
		);
	}

	/** function to check the Qshift hours (start/end time) exist within
	*	the start/end time of the Shift hours.
	*/	
	public function checkShiftQshiftHours($attribute,$params) {
	
		$shiftModel = Shift::model()->findByPk($this->idshift);
		$qshiftModel = QShift::model()->findByPk($this->idqshift);
		
		if(!( ( strtotime($qshiftModel->start_time) >= strtotime($shiftModel->start_time) )
			&& 
			( strtotime($qshiftModel->end_time) <= strtotime($shiftModel->end_time) ) )) 
		{	
			
			$this->addError('idqshift','<b>Error:</b> The <b>selected Q-Shift\'s hours</b> are <b>outside the Start/End times</b> of the <b>selected Shift!</b>');			
		}
	}	

	
	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'shift_relation' => array(self::BELONGS_TO, 'Shift', 'idshift'),
			'weekday_relation' => array(self::BELONGS_TO, 'Weekday', 'idweekday'),
			'user_relation' => array(self::BELONGS_TO, 'User', 'iduser'),
			'qshift_relation' => array(self::BELONGS_TO, 'Qshift', 'idqshift'),
			'team_relation' => array(self::BELONGS_TO, 'Team', 'team_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'iduser' => 'User',
			'idschedule' => 'Id',
			'team_id' => 'Team',
			'idshift' => 'Shift',
			'idqshift' => 'Q-Shift',
			'idweekday' => 'Weekday',			
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search($iduser=null)
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		if($iduser != null)
			$criteria->condition = 'iduser = '.$iduser;		
		
		$criteria->compare('idschedule',$this->idschedule);
		$criteria->compare('iduser',$this->iduser);
		$criteria->compare('team_id',$this->team_id);
		$criteria->compare('idshift',$this->idshift);
		$criteria->compare('idqshift',$this->idqshift);
		$criteria->compare('idweekday',$this->idweekday);
		$criteria->order = 'idweekday ASC';
		
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}	
	
	/**
	 * Retrieves the schedule for a user on a specific date
	 * @param user is the iduser of the user
	 * @param date is the date to get
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public static function getUserScheduleForDate($user, $date)
	{
		 //echo "user = $user date = $date"; exit;
		 
		 ///CHECK FOR NULL VALUES
		 		 
		/* Date Processing
		 * get date and check for user's schedules for that day (if
		 * any) in the shift change table
		 */
		
		$dateArray = explode('-',$date);
		$dateObject = new DateTime('NOW');
		$dateObject->setTimeZone(new DateTimeZone("America/Costa_Rica"));
		$dateObject->setDate($dateArray[0],$dateArray[1],$dateArray[2]);
		$timestamp = strtotime($dateObject->format('Y-m-d'));
		$dayOfWeek = date("N", $timestamp);		
		$dateTest = $dateObject->format('Y-m-d');
		
		$criteria=new CDbCriteria;
		$criteria->condition = "day_requested like '".$date."' 
								and (request_status= ". ShiftChange::STATUS_APPROVED ." or request_status=". ShiftChange::STATUS_PENDING_CANCEL .")
								and (requesting_user = '".$user."' or target_user = '".$user."')";
		
		//echo $criteria->condition;exit;
		
		$shiftChangeArray = ShiftChange::model()->findAll($criteria);
		
		$scheduleModel = Schedule::model()->findByAttributes(array('iduser' => $user, 'idweekday' => $dayOfWeek));
		
		//echo "user= $user , date= $dateTest, dayOfWeek = $dayOfWeek";exit;
		
		if (($scheduleModel==null) && ($shiftChangeArray == null)) {
			// this user doesn't have a schedule for that day of the week, nor a shift change return null
			return null;
			
		} elseif (($scheduleModel==null) && ($shiftChangeArray != null)) {
		
			// create an empty schedule container if a shift change exists but a schedule don't
			$scheduleModel = new Schedule();
			$scheduleModel->idschedule = null;
			$scheduleModel->iduser = $user;
			$scheduleModel->team_id = User::model()->findByPk($user)->team;
			$scheduleModel->idshift = null;
			$scheduleModel->idqshift = null;
			$scheduleModel->idweekday = $dayOfWeek;					
		}
		
		
		if ($shiftChangeArray != null) {
			
			//print_r($shiftChangeModel);exit;
			//echo $shiftChangeModel[0]->requesting_user;exit;
			
			foreach ($shiftChangeArray as $shiftChangeModel){
				//check to modify the record if this is the requestor 
				if($scheduleModel->iduser == $shiftChangeModel->requesting_user) {
					//check if qshift is different
					if (($scheduleModel->idshift == $shiftChangeModel->requested_shift)&&($scheduleModel->idqshift != $shiftChangeModel->requested_qshift))
						$scheduleModel->isQshiftChange = true;					
					//replace schedule shift and qshift for the one on the shift change model
					$scheduleModel->idshift = $shiftChangeModel->requested_shift;
					$scheduleModel->idqshift = $shiftChangeModel->requested_qshift;
					$scheduleModel->wasChanged = true;
					$scheduleModel->changeId = $shiftChangeModel->idshift_change;
				} 
				//check to modify the record if this is the target
				elseif ($scheduleModel->iduser == $shiftChangeModel->target_user ) {
					//replace schedule shift and qshift for the permanent schedule from the requesting_user
					$requestorSchedule = Schedule::model()->findByAttributes(array('iduser'=>$shiftChangeModel->requesting_user,'idweekday'=>$scheduleModel->idweekday));
					//check if qshift is different
					if (($scheduleModel->idshift == $requestorSchedule->idshift)&&($scheduleModel->idqshift != $requestorSchedule->idqshift))
						$scheduleModel->isQshiftChange = true;					
					$scheduleModel->idshift = $requestorSchedule->idshift;
					$scheduleModel->idqshift = $requestorSchedule->idqshift;	
					$scheduleModel->wasChanged = true;
					$scheduleModel->changeId = $shiftChangeModel->idshift_change;
				} 
			}
		}
		
		//echo $scheduleModel->idschedule;exit;
		
		return $scheduleModel;
	}	
	
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @param user is the iduser of the user
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function getUserWeekSchedule($user,$getArray = null,$week = null,$year=null)
	{
		/* Date Processing
		 * get today's date and check for user's schedules for those days (if
		 * any) in the shift change table
		 */	
				
		if ($week==null) {
			$today = new DateTime('NOW');
			$today->setTimeZone(new DateTimeZone("America/Costa_Rica"));
			$timestamp = strtotime($today->format('Y-m-d'));
			$mondayDate = date('Y-m-d',strtotime(date('o-\\WW')));
		} elseif ($year != null){
			//check for monday of the specified week and set the monday date
			$week_start = new DateTime();
			$week_start->setISODate($year,$week);
			$mondayDate = $week_start->format('Y-m-d');
			$tuesdayDate = date('Y-m-d',strtotime('next tuesday', $week_start->getTimestamp()));
			$wednesdayDate = date('Y-m-d',strtotime('next wednesday', $week_start->getTimestamp()));
			$thursdayDate = date('Y-m-d',strtotime('next thursday', $week_start->getTimestamp()));
			$fridayDate = date('Y-m-d',strtotime('next friday', $week_start->getTimestamp()));
			$saturdayDate = date('Y-m-d',strtotime('next saturday', $week_start->getTimestamp()));
			$sundayDate = date('Y-m-d',strtotime('next sunday', $week_start->getTimestamp()));
		} else
			throw new CHttpException(500,'Incorrect method usage for getUserWeekSchedule... contact michamen@cisco.com!');
		
		//echo "today= ".$today->format('Y-m-d')."monday= $mondayDate";exit;
		$mondayArray = explode('-', $mondayDate);		
		$tuesdayArray = explode('-', $tuesdayDate);		
		$wednesdayArray = explode('-', $wednesdayDate);		
		$thursdayArray = explode('-', $thursdayDate);		
		$fridayArray = explode('-', $fridayDate);		
		$saturdayArray = explode('-', $saturdayDate);		
		$sundayArray = explode('-', $sundayDate);		
		
		$criteria=new CDbCriteria;
		$criteria->condition = "day_requested between '".$mondayArray[0]."-".$mondayArray[1]."-".$mondayArray[2]."' 
												  and '".$sundayArray[0]."-".$sundayArray[1] ."-".($sundayArray[2])."'  
												  and ( request_status= ". ShiftChange::STATUS_APPROVED ." or request_status= ". ShiftChange::STATUS_PENDING_CANCEL .") 
												  and ( requesting_user = '".$user."' or target_user = '".$user."')";
		
		$shiftChangeModels = ShiftChange::model()->findAll($criteria);
		
		//print_r($shiftChangeModels);exit; //TESTER
		
		$scheduleModels = Schedule::model()->findAll(array('condition' => 'iduser = ' . $user, 'order'=>'idweekday ASC'));
		
		foreach($shiftChangeModels as $shiftChangeRecord) {
			//add weekday depending on date
			if ($shiftChangeRecord->day_requested == $mondayArray[0].'-'.$mondayArray[1].'-'.$mondayArray[2]) { 
				$shiftChangeRecord->weekday = Weekday::MONDAY;
			} elseif ($shiftChangeRecord->day_requested == $tuesdayArray[0].'-'.$tuesdayArray[1].'-'.($tuesdayArray[2])){ 
				$shiftChangeRecord->weekday = Weekday::TUESDAY;
			} elseif ($shiftChangeRecord->day_requested == $wednesdayArray[0].'-'.$wednesdayArray[1].'-'.($wednesdayArray[2])){ 
				$shiftChangeRecord->weekday = Weekday::WEDNESDAY;
			} elseif ($shiftChangeRecord->day_requested == $thursdayArray[0].'-'.$thursdayArray[1].'-'.($thursdayArray[2])){ 
				$shiftChangeRecord->weekday = Weekday::THURSDAY;
			} elseif ($shiftChangeRecord->day_requested == $fridayArray[0].'-'.$fridayArray[1].'-'.($fridayArray[2])){ 
				$shiftChangeRecord->weekday = Weekday::FRIDAY;
			} elseif ($shiftChangeRecord->day_requested == $saturdayArray[0].'-'.$saturdayArray[1].'-'.($saturdayArray[2])){ 
				$shiftChangeRecord->weekday = Weekday::SATURDAY;
			} elseif ($shiftChangeRecord->day_requested == $sundayArray[0].'-'.$sundayArray[1].'-'.($sundayArray[2])){ 
				$shiftChangeRecord->weekday = Weekday::SUNDAY;
			}
		}
		
		// 1) CHECK FOR EMPTY SCHEDULE DAYS FOR USER
		$weekdaysArray = Weekday::getWeekdays();
		
		foreach ($weekdaysArray as $day) {
			
			$weekdayFound = false;
			
			foreach($scheduleModels as $scheduleRecord) {
				if($scheduleRecord->idweekday == $day)
					$weekdayFound = true;							
			}
			
			// 2) ASSIGN NULL MODEL IF EMPTY AND SHIFT CHANGE FOUND FOR THAT DAY
			if(!$weekdayFound){
				$shiftChangeFound = false;
				
				foreach($shiftChangeModels as $shiftChangeRecord){
					if($shiftChangeRecord->weekday == $day)
						$shiftChangeFound = true;
				}
				
				if($shiftChangeFound){
					$newModel = new Schedule();
					$newModel->idschedule = null;
					$newModel->iduser = $user;
					$newModel->team_id = User::model()->findByPk($user)->team;
					$newModel->idshift = null;
					$newModel->idqshift = null;
					$newModel->idweekday = $day;
					
					// 3) ADD empty schedule to $scheduleModels
					$scheduleModels[] = $newModel;
				}
			}
		}
	
		foreach($scheduleModels as $scheduleRecord) {
			
			foreach($shiftChangeModels as $shiftChangeRecord) {
					
					//check to modify the record if this is the requestor for the same weekday
					if( ($scheduleRecord->iduser == $shiftChangeRecord->requesting_user)&&($scheduleRecord->idweekday == $shiftChangeRecord->weekday) ){
						//check if qshift is different
						if (($scheduleRecord->idshift == $shiftChangeRecord->requested_shift)&&($scheduleRecord->idqshift != $shiftChangeRecord->requested_qshift))
							$scheduleRecord->isQshiftChange = true;	
						//replace schedule shift and qshift for the one on the shift change model
						$scheduleRecord->idshift = $shiftChangeRecord->requested_shift;
						$scheduleRecord->idqshift = $shiftChangeRecord->requested_qshift;
						$scheduleRecord->wasChanged = true;
						$scheduleRecord->changeId = $shiftChangeRecord->idshift_change;
					} 
					//check to modify the record if this is the target for the same weekday
					elseif ( ($scheduleRecord->iduser == $shiftChangeRecord->target_user)&&($scheduleRecord->idweekday == $shiftChangeRecord->weekday) ) {
						//check if qshift is different
						$requestorSchedule = Schedule::model()->findByAttributes(array('iduser'=>$shiftChangeRecord->requesting_user,'idweekday'=>$scheduleRecord->idweekday));
						if (($scheduleRecord->idshift == $requestorSchedule->idshift)&&($scheduleRecord->idqshift != $requestorSchedule->idqshift))
							$scheduleRecord->isQshiftChange = true;						
						//replace schedule shift and qshift for the permanent schedule from the requesting_user
						$scheduleRecord->idshift = $requestorSchedule->idshift;
						$scheduleRecord->idqshift = $requestorSchedule->idqshift;	
						$scheduleRecord->wasChanged = true;
						$scheduleRecord->changeId = $shiftChangeRecord->idshift_change;
					}
			}
		}
				
		if($getArray==null) { 
			$dataProvider=new CArrayDataProvider($scheduleModels, array(
				'keyField'=>'idschedule',
				/*
				'sort'=>array(
					'attributes'=>array(
						 'id', 'username', 'email',
					),
				), */
				'pagination'=>array(
					'pageSize'=>7,
				),
			));
			
			return $dataProvider;
			
			// $dataProvider->getData() will return a list of arrays.		
			// http://www.yiiframework.com/doc/api/1.1/CArrayDataProvider
		} elseif($getArray) {
			
			//print_r($scheduleModels); 
			
			return $scheduleModels;
		}
	}
	
	
	public static function getTeamScheduleDateStats($teamId, $date, $getArray=null) {
				
		// get list of enabled users 
		$userArray = User::model()->findAll(array('condition'=>'enabled = 1 and team = ' . $teamId));
		
		if ($userArray == null)
			return null;
			
		// get schedules for enabled users intro array
		
		$schedulesArray = array();
		
		foreach ($userArray as $user) {
			
			$userSchedule = Schedule::getUserScheduleForDate($user->iduser, $date);
			
			
			if (!($userSchedule == null))
				$schedulesArray[] = $userSchedule;
		}
		
		
		// traverse schedule arrays to 
		//  - increase total counters to a variable
		
		$childMainArray = array();
		
		foreach ($schedulesArray as $schedule) {
			
			//echo "entering with user $schedule->iduser, shift $schedule->idshift, qshift $schedule->idqshift<br><br>"; //***TESTER
			
			$shiftModel = $schedule->shift_relation;
			$qshiftModel = $schedule->qshift_relation;  
			
			//check if key with this shift id exists already
			if( !(array_key_exists($schedule->idshift, $childMainArray)) ) {
				
				//echo "Created shift key for $schedule->idshift ! <br>";  //***TESTER
				
				$childMainArray[$schedule->idshift] = array();	
				
			} //shift key created
			
			
			//check if key with this q-shift id exists already, create if not
			if( !(array_key_exists($schedule->idqshift, $childMainArray[$schedule->idshift])) ){
				
				
				//echo "Created qshift key for $schedule->idqshift ! with shift key $schedule->idshift <br><br>"; //***TESTER

				//creating qshift arrays for current shift array key
				$childMainArray[$schedule->idshift][$schedule->idqshift] = array ();
				$childMainArray[$schedule->idshift][$schedule->idqshift]['members'] = array();
				$childMainArray[$schedule->idshift][$schedule->idqshift]['count'] = 0;
			} // qshift key created
			
			$childMainArray[$schedule->idshift][$schedule->idqshift]['shift_name'] = $shiftModel->name;		
			
			if($shiftModel->availability){ //if not available show empty times
				$childMainArray[$schedule->idshift][$schedule->idqshift]['shift_start_time'] = $shiftModel->start_time;
				$childMainArray[$schedule->idshift][$schedule->idqshift]['shift_end_time'] = $shiftModel->end_time;
			} else {
				$childMainArray[$schedule->idshift][$schedule->idqshift]['shift_start_time'] = "--:--";
				$childMainArray[$schedule->idshift][$schedule->idqshift]['shift_end_time'] = "--:--";
			}	
			$childMainArray[$schedule->idshift][$schedule->idqshift]['qshift_name'] = $qshiftModel->name;
			
			if($qshiftModel->availability) {//if not available show empty times
				$childMainArray[$schedule->idshift][$schedule->idqshift]['qshift_start_time'] = $qshiftModel->start_time;
				$childMainArray[$schedule->idshift][$schedule->idqshift]['qshift_end_time'] = $qshiftModel->end_time;	
			} else {
				$childMainArray[$schedule->idshift][$schedule->idqshift]['qshift_start_time'] = "--:--";
				$childMainArray[$schedule->idshift][$schedule->idqshift]['qshift_end_time'] = "--:--";				
			}
			
			$childMainArray[$schedule->idshift][$schedule->idqshift]['qshift_availability'] = $qshiftModel->availability;				
			
			//increment counter and save iduser to members array
			$childMainArray[$schedule->idshift][$schedule->idqshift]['count'] += 1;
			$childMainArray[$schedule->idshift][$schedule->idqshift]['members'][] = $schedule->iduser;
			
		}
		
					//print_r($childMainArray);  ///************TESTER

		
		//arrange data into parent array for data provider
		
		$parentMainArray = array();
		
		//iterate through shifts
		foreach ($childMainArray as $keyShift => $valueShift) {
			
			//iterate through qshifts
			foreach ( $valueShift as $keyQshift => $valueQshift) {
				
				$membersText = '';
								
				//iterate through members
				foreach ( $valueQshift['members'] as $member) {
					
					$membersText .= ','.$member;
				}
				
				//ADD ALL DATA TO SINGLE ENTRY IN parentMainArry
				$parentMainArray[] = array(
											'idshift' => $keyShift,
											'shift_name' => $valueQshift['shift_name'],
											'shift_start_time' => $valueQshift['shift_start_time'],
											'shift_end_time' => $valueQshift['shift_end_time'],
											'idqshift' => $keyQshift,
											'qshift_name' => $valueQshift['qshift_name'],
											'qshift_start_time' => $valueQshift['qshift_start_time'],
											'qshift_end_time' => $valueQshift['qshift_end_time'],											
											'qshift_availability' => $valueQshift['qshift_availability'],											
											'total' => $valueQshift['count'],
											'members' => $membersText
											);
			}
		
		}
		
			//print_r($parentMainArray); ///************ TESTER
		
		//sort results by qshift start time

		// Obtain a list of columns
		foreach ($parentMainArray as $key => $row) {
			$availability[$key]  = $row['qshift_availability'];
			$startTime[$key]  = $row['qshift_start_time'];
		}

		// Sort the data with start time descending
		// Add $parentMainArray as the last parameter, to sort by the common key
		array_multisort($availability, SORT_DESC, $startTime, SORT_ASC, $parentMainArray);		

		if($getArray==null) { 
			// create data provider
			$dataProvider=new CArrayDataProvider($parentMainArray, array(
				'keyField'=>'idqshift',
				/*
				'sort'=>array(
					'attributes'=>array(
						 'id', 'username', 'email',
					),
				), */
				'pagination'=>array(
					'pageSize'=>10,
				),
			));
			
			return $dataProvider;		

		} elseif($getArray)
			return $parentMainArray;

		
	}
	
	
	public static function getTeamScheduleDateAvailabilityShiftCount($teamId, $date, $getArray=null) {
				
		// get list of enabled users 
		$userArray = User::model()->findAll(array('condition'=>'enabled = 1 and team = ' . $teamId));
		
		if ($userArray == null)
			return null;
			
		// get schedules for enabled users intro array
		
		$schedulesArray = array();
		
		foreach ($userArray as $user) {
			
			$userSchedule = Schedule::getUserScheduleForDate($user->iduser, $date);
			
			
			if (!($userSchedule == null))
				$schedulesArray[] = $userSchedule;
		}
		
		
		// traverse schedule arrays to 
		//  - increase total counters to a variable
		
		$childMainArray = array();
		
		foreach ($schedulesArray as $schedule) {
			
			//echo "entering with user $schedule->iduser, shift $schedule->idshift, qshift $schedule->idqshift<br><br>"; //***TESTER
			
			$shiftModel = $schedule->shift_relation;
			
			//check if key with this shift id exists already
			if( !(array_key_exists($schedule->idshift, $childMainArray)) ) {
				
				//echo "Created shift key for $schedule->idshift ! <br>";  //***TESTER
				$childMainArray[$schedule->idshift] = array();	
				$childMainArray[$schedule->idshift]['count'] = 0;
			} //shift key created
			
			//increment counter 
			if($shiftModel->availability) {//if not available show empty times
				$childMainArray[$schedule->idshift]['count'] += 1;
			}			
		}
		

		//arrange data into parent array for data provider
		$parentMainArray = array();
		
		//iterate through shifts
		foreach ($childMainArray as $keyShift => $valueShift) {
			
			
			$parentMainArray[] = array(
										'idshift' => $keyShift,
										'total' => $valueShift['count'],
										);
		}
		
			//print_r($parentMainArray); ///************ TESTER
		
		return $parentMainArray;
	}	
	
}